<?php

namespace falcon5\inc\Http\Views;

/**
 * Class View
 * @package falcon5\inc\Http\Views
 */
class View implements ViewInterface
{
    private $template;
    private $data;

    /**
     * View constructor.
     * @param string $template
     * @param array $data
     */
    public function __construct(string $template, array $data = [])
    {
        $this->template = $template;
        $this->data = $data;
    }

    /**
     * 分配变量到模板
     * @param array $params
     * @return void
     */
    public function assign(array $params = [])
    {
        $this->data = array_merge($this->data, $params);
    }

    /**
     * 渲染模板
     * @param array $params
     * @return string
     */
    public function render(array $params = []): string
    {
        $templatePath = $this->getTemplatePath();
        if (!file_exists($templatePath)) {
            throw new \RuntimeException("Template file not found: {$templatePath}");
        }

        ob_start();
        extract($this->data);
        include $templatePath;
        return ob_get_clean();
    }

    /**
     * 获取模板文件路径
     * @return string
     */
    private function getTemplatePath(): string
    {
        return plugin_dir_path(dirname(__FILE__, 3)) . 'templates/' . $this->template . '.php';
    }
}